/**
 * 
 */
package info.niwota.frames;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;

/**
 * @author qiangli
 * 
 */
public class ImageUtils {

	private static final String TAG = "ImageUtils";

	private ImageUtils() {
	}
	
	public static void thumbnail(File from, File to) throws IOException {
		transform(from, to, 75, 75, CompressFormat.JPEG, 70);
	}

	public static void vignette(File from, File to) throws IOException {
		transform(from, to, 250, 250, CompressFormat.JPEG, 70);
	}
	
	public static void transform(File from, File to, int width, int height,
			CompressFormat format, int quality) throws IOException {
		final String path = from.getPath();
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, opt);
		int w = opt.outWidth;
		int h = opt.outHeight;

		if (w == -1 || h == -1) {
			throw new IOException("can not decode width/height");
		}
		
		float scalew = w / width;
		float scaleh = h / height;
		
		int scale = (int) Math.max(scalew, scaleh);

		opt.inJustDecodeBounds = false;
		opt.inSampleSize = scale;
		opt.inDither = false;
		opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
		
		Bitmap bm = BitmapFactory.decodeFile(path, opt);

		FileOutputStream out = null;
		try {
			out = new FileOutputStream(to);
			bm.compress(format, quality, out);
		} finally {
			bm.recycle();
			
			if (out != null) {
				out.close();
			}
		}
		if (Debug.DEBUG) {
			Log.d(TAG, "Image: "+ from.getPath() + " original: "+ from.length() + " compressed: " + to.length());
		}
	}

	public static BitmapFactory.Options sniffOptions(String file) {
		try {
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(file, opts);
			return opts;
		} finally {
			//
		}
	}
}
